﻿using AuthCenter.Api.Write.Application.Command.User;
using AuthCenter.Application;
using AuthCenter.Domain;
using AuthCenter.ErrorCode;
using AutoMapper;
using MediatR;

namespace AuthCenter.Api.Write.Application.Hander.User
{
    public class AddUserHander:IRequestHandler<AddUserCommand,ApiResult<int>>
    {
        private readonly IBaseRepository<UserModel> _userRepository;
        private readonly IBaseRepository<ProvinceModel> _provinceRepository;
        private readonly IMapper _mapper;
        private readonly IBaseRepository<CityModel> _cityRepository;
        private readonly IBaseRepository<CountyModel> _countyRepository;
        private readonly IBaseRepository<RoleModel> _roleRepository;
        private readonly IBaseRepository<UserRoleModel> _userRoleRepository;
        public AddUserHander(IBaseRepository<UserModel> userRepository, IMapper mapper, IBaseRepository<ProvinceModel> provinceRepository, IBaseRepository<CityModel> cityRepository, IBaseRepository<CountyModel> countyRepository, IBaseRepository<RoleModel> roleRepository, IBaseRepository<UserRoleModel> userRoleRepository)
        {
            _userRepository = userRepository;
            _mapper = mapper;
            _provinceRepository = provinceRepository;
            _cityRepository = cityRepository;
            _countyRepository = countyRepository;
            _roleRepository = roleRepository;
            _userRoleRepository = userRoleRepository;
        }
        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public Task<ApiResult<int>> Handle(AddUserCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> res = new ApiResult<int>();
            var user = _userRepository.GetAll().Where(x => x.UserName == request.UserName && x.IsDeleted == false).FirstOrDefault();
            if (user != null)
            {

                res.Code = ApiEnums.Error;
                res.Message = "用户已存在";
                return Task.FromResult(res);
                
            }

            var model = _mapper.Map<UserModel>(request);
            model.Password = string.Empty;
            model.CreateTime = DateTime.Now;
            model.CreateUserName = request.UserName;
            model.Password = "123456";
            int i=_userRepository.Create(model);
            if (i > 0)
            {
                res.Code = ApiEnums.OK;
                res.Message = "添加成功";
                res.Data = i;
            }
            else 
            {
                res.Code = ApiEnums.Fail;
                res.Message = "添加失败";
                res.Data = 1;
            }
            return Task.FromResult(res);            
        }
    }
}
